package com.zwh.rocketmq.demo.order;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zwh
 * @date 2024-1-18 23:19
 */
@Service
public class OrderMessageProduct {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /*
      发送顺序消息
     */
    public void sendOrderMsg() {
        String destination = "TEST_ORDER_TOPIC";
        String tags = "tag1";
//        String msgBody = "hello rocketMQ";
//        String keys = "orderId1";
        if (StringUtils.isNotBlank(tags)) {
            // 带tag的消息，直接在topic后面加上":tag"， 底层会进行自动转换
            destination = destination + ":" + tags;
        }

        for(int i=0; i<100; i++) {
            Map<String, Object> msgData1 = new HashMap<>();
            msgData1.put("operator", "订单生成");
            Map<String, Object> msgData2 = new HashMap<>();
            msgData2.put("operator", "订单付款");
            Map<String, Object> msgData3 = new HashMap<>();
            msgData3.put("operator", "订单发货");

            msgData1.put("orderId", i);
            msgData2.put("orderId", i);
            msgData3.put("orderId", i);
            Message<Map<String, Object>> message1 = MessageBuilder.withPayload(msgData1)
                    .setHeader(RocketMQHeaders.KEYS, i)
                    .build();
            // 同步发送
            // 同步发送方式请务必捕获发送异常，并做业务侧失败兜底逻辑，如果忽略异常则可能会导致消息未成功发送的情况。
            rocketMQTemplate.syncSendOrderly(destination, message1, String.valueOf(i));

            Message<Map<String, Object>> message2 = MessageBuilder.withPayload(msgData2)
                    .setHeader(RocketMQHeaders.KEYS, i)
                    .build();
            rocketMQTemplate.syncSendOrderly(destination, message2, String.valueOf(i));

            Message<Map<String, Object>> message3 = MessageBuilder.withPayload(msgData3)
                    .setHeader(RocketMQHeaders.KEYS, i)
                    .build();
            rocketMQTemplate.syncSendOrderly(destination, message3, String.valueOf(i));
        }
    }
}
